import { ApiResponse, loginType, tokenType } from '@/types/data';
import { loginAction, rootThunkAction } from '@/types/store';
import http from '@/utils/request';
import { clearToken, setToken } from '@/utils/tokens';
/**登录存储token */
export const login = (data: loginType): rootThunkAction => {
  return async (dispatch) => {
    const res = await http.post<ApiResponse<tokenType>>(
      '/authorizations',
      data
    );
    // console.log(res);
    //redux存储token
    dispatch(gettingToken(res.data.data));
  };
};

/**获取token业务 */
export const gettingToken = (token: tokenType): loginAction => {
  // 本地存储token
  setToken(token);
  return {
    type: 'login/login',
    payload: token,
  };
};
/**发请求发送验证码 */
export const getCode = (mobile: string): rootThunkAction => {
  return async (dispatch) => {
    await http.get(`/sms/codes/${mobile}`);
  };
};

/**清空token */
export const removeToken = (): loginAction => {
  //清空本地的token
  clearToken();
  //清空redux里面的token
  return { type: 'login/logout' };
};
